package com.ysd.lis.service.emr.impl;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ysd.common.Result;
import com.ysd.lis.entity.emr.EmrItemStandardTaskFile;
import com.ysd.lis.mapper.emr.EmrItemStandardTaskFileMapper;
import com.ysd.lis.request.emr.EmrParam;
import com.ysd.lis.service.emr.EmrItemStandardTaskFileService;
import com.ysd.util.PropertySlash;
import com.ysd.util.ToolsUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.*;


/**
 * <p>
 * cold_chain.sys_Model 服务实现类
 * </p>
 *
 * @author prs
 * @since 2024-12-27
 */
@Service
public class EmrItemStandardTaskFileServiceImpl extends ServiceImpl<EmrItemStandardTaskFileMapper, EmrItemStandardTaskFile> implements EmrItemStandardTaskFileService {

    @Autowired
    EmrItemStandardTaskFileMapper emrItemStandardTaskFileMapper;
    @Override
    public Result findItemStandardTaskFileList(EmrParam param) {
        LambdaQueryWrapper<EmrItemStandardTaskFile> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(EmrItemStandardTaskFile::getDelFlag,0)
                .eq(EmrItemStandardTaskFile::getTaskId,param.getTaskId());
        List<EmrItemStandardTaskFile> taskFileList = emrItemStandardTaskFileMapper.selectList(queryWrapper);
        if(ToolsUtils.isNotEmpty(taskFileList)){
            return Result.succ(1, "查询成功", taskFileList.get(0));
        }else {
            return Result.succ(1, "查询成功", null);

        }
    }
    @Value("${emrFilePath}")
    private String emrFilePath;

    @Override
    public Map<String, Integer> saveFile(HttpServletRequest request) throws IOException {
        // 任务id
        String id = request.getParameter("id");
        String taskId = request.getParameter("taskId");
        String orgId = request.getParameter("orgId");
        String body = "";
        try {
            Scanner scanner = new Scanner(request.getInputStream());
            scanner.useDelimiter("\\A");
            body = scanner.hasNext() ? scanner.next() : "";
            scanner.close();
        } catch (Exception ex) {
            return new HashMap<>();
        }
        if (body.isEmpty()) {
            throw new IOException("ONLYOFFICE回调保存请求体未空");
        }

        JSONObject jsonObj = JSONUtil.parseObj(body);
        int status = jsonObj.getInt("status");

        if (status == 2 || status == 3 || status == 6) {
            String serverFielUrl = jsonObj.getStr("url");
            String fileName = taskId + ".docx";
            getFile(serverFielUrl, emrFilePath + PropertySlash.getSlash() + "emr" + PropertySlash.getSlash() + fileName);
            //根据taskId删除之前的
            this.remove(new LambdaQueryWrapper<EmrItemStandardTaskFile>().eq(EmrItemStandardTaskFile::getTaskId, taskId).eq(EmrItemStandardTaskFile::getDelFlag, 0));
            EmrItemStandardTaskFile emrItemStandardTaskFile = new EmrItemStandardTaskFile();
            emrItemStandardTaskFile.setId(id);
            emrItemStandardTaskFile.setTaskId(taskId);
            emrItemStandardTaskFile.setFileName(taskId);
            emrItemStandardTaskFile.setFileUrl("/wordFile/emr/" + fileName);
            emrItemStandardTaskFile.setFileExt("docx");
            emrItemStandardTaskFile.setOrgId(orgId);
            this.saveOrUpdate(emrItemStandardTaskFile);
        }

        return Collections.singletonMap("error", 0);
    }

    // 更新文件
    void getFile(String remoteFilePath, String localFilePath) throws IOException {
        Path targetPath = Paths.get(localFilePath);

        // 自动创建目录
        if (!Files.exists(targetPath.getParent())) {
            Files.createDirectories(targetPath.getParent());
        }

        try (InputStream in = new URL(remoteFilePath).openStream()) {
            Files.copy(in, targetPath, StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e) {
            throw e;
        }
    }
}
